const express = require('express');

const router = express.Router();

const User=require('../model/user')

// 添加用户
router.post('/add', async (req, res) => {
    const { wxInfo, phone,wxNickName, wxHeadPhoto, wxOpenId  } = req.body;
    // console.log(wxInfo);


    // 数据过滤
    if (!wxNickName || !wxNickName || !wxOpenId) return res.send({ success: false, info: '请填写指定参数' });
    if (/^1(3456789)\d{9}$/.test(phone)) return res.send({ success: false, info: '请填正确的手机号码' });
    
    //添加入库
    try {
        const one = await User.findOne({ phone });//找不到的话返回null
        if (one) return res.send({ success: false, info: '当前手机号码已经被占用' });
        
        await User.create({
            wxNickName,
            wxHeadPhoto,
            wxOpenId,
            phone,
            wxInfo
        })
        res.send({success:true,info:'添加成功'})
    } catch (error) {
        res.send({ success: false, info: '未知错误,请与网站管理员联系' })
    }
})

// 修改用户
router.post('/edit', async (req, res) => {
    const { phone,wxOpenId  } = req.body;

    if(!wxOpenId) return res.send({ success: false, info: '请填写指定参数' })

    if (/^1(3456789)\d{9}$/.test(phone)) return res.send({ success: false, info: '请填正确的手机号码' });

    let updateDate = { phone };
       
    //执行修改
    try {
        await User.findOneAndUpdate({wxOpenId,
        },updateDate)
        res.send({success:true,info:'修改成功'})
    } catch (error) {
        res.send({ success: false, info: '未知错误,请与网站管理员联系' })
    }
})


module.exports = router;